// import legacy from "@vitejs/plugin-legacy"
import react from "@vitejs/plugin-react";
import { defineConfig, loadEnv } from "vite"

import path from 'path';

type EnvDetail = {
  VITE_BASE_API?: '/devapi'
}


//command:dev/build/preview, mode:development/production
export default defineConfig(({ command, mode }) => {
  const cwd = process.cwd()
  const envDetail: EnvDetail = loadEnv(mode, path.resolve(cwd, "env"), "VITE");
  console.warn('--envDetail--:', envDetail);
  return {
    define: {
      'process.env': process.env, //不然打包后 process is undefined
    },
    plugins: [
      react({
        // babel: {
        // presets: [
        //   '@babel/preset-react',
        //   {
        //     runtime: 'automatic', // 不用 import React 也可使用react
        //   },
        // ]
        // }
      }),
      // legacy({
      //   targets: ["defaults", "not IE 11"] // 报错@vitejs/plugin-legacy does not support library mode.
      // }),
    ],
    envDir: path.resolve(cwd, "env"),  //默认根目录下的env
    css: {
      preprocessorOptions: {
        less: {
          javascriptEnabled: true,
          // modifyVars: {
          //   "primary-color": "#F66E2C"
          // }
        }
      }
    },
    resolve: {
      alias: [
        {
          find: "@",
          replacement: path.resolve(cwd, "src")
        },
      ]
    },
    base: mode === 'development' ? "/" : '/bigScreen', //类似 output.publicPath,在项目中可通过 import.meta.env.BASE_URL获取
    build: {
      emptyOutDir: true,
      outDir: path.resolve(cwd, "bigScreen"),
      lib: {
        entry: path.resolve(cwd, "src/index.tsx"),
        name: 'bigScreen',
        fileName: 'bigScreen',
        formats: ['es']
      },
      rollupOptions: {
        input: path.resolve(cwd, 'index.html'), // 确保这里指向你的入口HTML文件
        output: {
          format: 'es',
        }
      },
    },
    server: {
      open: true,
      port: 4005,
      proxy: {
        '/devapi': {
          target: 'http://mp.test2.logibeat.com',
          // target: 'http://api-pre.logibeat.com',
          changeOrigin: true,
          rewrite: (path) => path.replace(/^\/devapi/, "")
        },
      }
    }
  }
})
